#!/bin/bash

set -ex

cur_dir=$(dirname "$(readlink -f "$0")")

# 读取并解析 JSON 数据
ips=$(jq -r '.ips | .[]' config.json)
user=$(jq -r '.user' config.json)
password=$(jq -r '.password' config.json)
port=$(jq -r '.port' config.json)
sh_files=$(jq -r '.command | .[]' config.json)  # 获取所有需要执行的脚本文件名

# 远程目录
remote_dir="/tmp/ops-tools"
# 远程执行命令所在目录
tools_dir="tools"
logs_dir="logs"
timestamp=$(date +%Y-%m-%d_%H-%M-%S)

pushd "$cur_dir" || exit
mkdir -p "$logs_dir"
for ip in $ips; do
    sshpass -p "$password" ssh -o StrictHostKeyChecking=no -p "$port" "$user@$ip" \
        "mkdir -p $remote_dir"

    if command -v rsync &> /dev/null; then
        rsync -az -e "sshpass -p $password ssh -o StrictHostKeyChecking=no -p $port" \
            "${tools_dir}/"* "$user@$ip:$remote_dir" &
    else
        sshpass -p "$password" scp -P "$port" -r "$tools_dir" "$user@$ip:$remote_dir" &
    fi
done
wait

for ip in $ips; do
    for sh_file in $sh_files; do
        echo "执行 $sh_file ..."
        log_file="$ip"-$(basename "$sh_file" ".sh")-"$timestamp".log
        sshpass -p "$password" ssh -o StrictHostKeyChecking=no -p "$port" "$user@$ip" \
            "cd $remote_dir/$tools_dir && chmod +x $sh_file && echo '$password' | sudo -S bash $sh_file" \
            > "$logs_dir"/"$log_file" 2>&1 &
    done
done
wait

echo "Done"
popd || exit
